<template>
  <div class="page">
    <Header />
    <div class="registration-page">
      <div class="back-link">
        <el-link class="more" @click="navto('/login')" type="primary" icon="DArrowLeft">返回</el-link>
        <span> 首页 / 注册</span>
      </div>

      <div class="form-container gradient-box">
        <div class="form">
          <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="form" label-width="140px">
            <el-form-item label="供应商经营资质证书类型" prop="certType">
              <el-select v-model="form.certType" placeholder="请选择资质证书类型">
                <el-option
                  v-for="option in supplierCertOptions"
                  :key="option.dictValue"
                  :label="option.dictLabel"
                  :value="option.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="营业执照或资质证明证书" prop="businessLicense">
              <UploadItem
                :action="`${config.baseUrl}/common/upload`"
                :fileList="form.businessLicense"
                fileKey="businessLicense"
                @onSuccess="handleUploadSuccess"
                @onRemove="handleRemove"
                @onPreview="handlePreview"
                :limit="1"
              />
              <div style="margin-left: 10px; line-height: 1.6" v-if="!form.businessLicense.length">
                <span style="color: #ecac00; font-weight: bold">证件要求</span><br />
                <span style="font-size: 12px">必须为清晰，完整的原件扫描件或数码照， </span><br />
                <span style="font-size: 12px">仅支持JPG、PNG的图片格式，且不超过1M </span><br />
                <span style="font-size: 12px">必须在有效期内且年检章齐全</span><br />
              </div>
            </el-form-item>
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
            <el-form-item label="单位名称" prop="enterprise">
              <el-input v-model="form.enterprise" placeholder="请输入单位名称" />
            </el-form-item>
            <el-form-item label="有效期" prop="periodOfValidity">
              <div style="display: flex; align-items: center">
                <el-date-picker
                  v-model="form.periodOfValidity"
                  type="date"
                  placeholder="请选择有效期"
                  :disabled="form.isLongTime == 1"
                  style="flex: 1; margin-right: 10px"
                />
                <el-checkbox v-model="form.isLongTime" :true-label="1" :false-label="0" @change="handleLongTimeChange"> 长期 </el-checkbox>
              </div>
            </el-form-item>

            <el-form-item label="行业类别" prop="industryType">
              <el-checkbox-group v-model="form.industryType">
                <el-checkbox
                  v-for="option in supplierIndustryOptions"
                  :key="option.dictValue"
                  :label="option.dictLabel"
                  :value="option.dictValue"
                />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="住所" prop="address">
              <el-input v-model="form.address" placeholder="请输入住所" />
            </el-form-item>
            <el-form-item label="法人代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法人代表人姓名" />
            </el-form-item>
            <el-form-item label="是否独立法人" prop="independentLegalEntity">
              <el-radio-group v-model="form.independentLegalEntity">
                <el-radio value="1" size="large">是</el-radio>
                <el-radio value="0" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="法人授权书（即法人授权供应商主要联系人）" prop="authorization">
              <UploadItem
                :action="`${config.baseUrl}/common/upload`"
                :fileList="form.authorization"
                fileKey="authorization"
                @onSuccess="handleUploadSuccess"
                @onRemove="handleRemove"
                @onPreview="handlePreview"
                :limit="1"
              />
              <div style="margin-left: 10px; line-height: 1.6" v-if="!form.authorization.length">
                <span style="color: #ecac00; font-weight: bold">证件要求</span><br />
                <span style="font-size: 12px">必须为清晰，完整的原件扫描件或数码照， </span><br />
                <span style="font-size: 12px">仅支持JPG、PNG的图片格式，且不超过1M </span><br />
                <span style="font-size: 12px">必须在有效期内且年检章齐全</span><br />
              </div>
            </el-form-item>
            <el-form-item label="供应商主要联系人" prop="name">
              <el-input v-model="form.name" placeholder="请输入主要联系人姓名" />
            </el-form-item>
            <el-form-item label="供应商主要联系人电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系人电话" />
            </el-form-item>
            <el-form-item label="单位电子邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入单位电子邮箱" />
            </el-form-item>
            <el-form-item label="单位类型" prop="unitType">
              <el-select v-model="form.unitType" placeholder="请选择单位类型">
                <el-option v-for="option in unitTypeOptions" :key="option.dictValue" :label="option.dictLabel" :value="option.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item label="单位性质" prop="unitProperty">
              <el-select v-model="form.unitProperty" placeholder="请选择单位性质">
                <el-option
                  v-for="option in unitPropertyOptions"
                  :key="option.dictValue"
                  :label="option.dictLabel"
                  :value="option.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="资质等级附件" prop="certLevel">
              <UploadItem
                :action="`${config.baseUrl}/common/upload`"
                :fileList="form.certLevel"
                fileKey="certLevel"
                @onSuccess="handleUploadSuccess"
                @onRemove="handleRemove"
                @onPreview="handlePreview"
                :limit="1"
              />
              <div style="margin-left: 10px; line-height: 1.6" v-if="!form.certLevel.length">
                <span style="color: #ecac00; font-weight: bold">证件要求</span><br />
                <span style="font-size: 12px">必须为清晰，完整的原件扫描件或数码照， </span><br />
                <span style="font-size: 12px">仅支持JPG、PNG的图片格式，且不超过1M </span><br />
                <span style="font-size: 12px">必须在有效期内且年检章齐全</span><br />
              </div>
            </el-form-item>
            <el-form-item label="设置密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入8位及以上密码" />
              <span class="tips">密码至少包含大小写字母、数字、特殊字符的其中2种</span>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" />
              <span class="tips">密码至少包含大小写字母、数字、特殊字符的其中2种</span>
            </el-form-item>
            <el-form-item prop="code" label="验证码" v-if="captchaEnabled">
              <div class="register-tip">
                <el-input v-model="form.code" auto-complete="off" placeholder="验证码" style="flex: 0.9">
                  <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                </el-input>

                <div class="register-code">
                  <img :src="codeUrl" @click="getCode" class="register-code-img" />
                </div>
              </div>
            </el-form-item>
            <el-form-item prop="agreement">
              <el-checkbox v-model="form.agreement"
                >本人谨代表我单位承认以上内容真实有效，如出现弄虚作假情况，愿承担一切后果或责任！</el-checkbox
              >
            </el-form-item>
            <el-form-item>
              <el-button style="width: 100%; height: 42px; background: #347ff7" type="primary" @click="onSubmit"> 下一步 </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" style="width: 100%" alt="Preview Image" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import moment from "moment";
import { onMounted, ref } from "vue";
import { useDataStore } from "@/store/index.js"; // 引入 Pinia Store
import { showMessage } from "../../utils/common";
import Header from "../../components/Header.vue";
import { useRouter, useRoute } from "vue-router";
import { getCodeImg } from "@/api/login";
import config from "../../utils/config";
import { addVender } from "@/api/vendor";
import UploadItem from "@/components/UploadItem.vue";
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const dataStore = useDataStore(); // 使用 Pinia Store

const codeUrl = ref("");
const dialogVisible = ref(false);
const dialogImageUrl = ref("");
const captchaEnabled = ref(false);
const router = useRouter();
const route = useRoute();
const type = computed(() => route.query.type);
const formRef = ref(null);
const form = ref({
  certType: "",
  businessLicense: [],
  creditCode: "",
  enterprise: "",
  periodOfValidity: "",
  industryType: [],
  address: "",
  legalRepresentative: "",
  independentLegalEntity: "",
  name: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
  code: "",
  agreement: "",
  authorization: [],
  certLevel: [],
  isLongTime: 0,
});
// 从 Store 中获取字典数据
const supplierCertOptions = computed(() => dataStore.supplier_cert);
const supplierIndustryOptions = computed(() => dataStore.supplier_industry);
const unitTypeOptions = computed(() => dataStore.unit_type);
const unitPropertyOptions = computed(() => dataStore.unit_property);

const rules = {
  certType: [{ required: true, message: "请选择资质证书类型", trigger: "change" }],
  businessLicense: [{ required: true, message: "请上传营业执照或资质证明证书", trigger: "change" }],
  authorization: [{ required: true, message: "请上传法人授权书", trigger: "change" }],
  // certLevel: [{ required: true, message: "请上传资质等级附件", trigger: "change" }],
  creditCode: [{ required: true, message: "统一社会信用代码不能为空", trigger: "blur" }],
  enterprise: [{ required: true, message: "单位名称不能为空", trigger: "blur" }],
  periodOfValidity: [
    {
      required: true,
      message: "请选择有效期",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (form.value.isLongTime == 1) {
          callback(); // 长期选中时直接通过验证
        } else if (!value) {
          callback(new Error("请选择有效期")); // 长期未选中且未选择日期时触发验证错误
        } else {
          callback(); // 验证通过
        }
      },
    },
  ],
  industryType: [{ required: true, message: "请选择行业类别", trigger: "change" }],
  address: [{ required: true, message: "住所不能为空", trigger: "blur" }],
  legalRepresentative: [{ required: true, message: "法人代表人不能为空", trigger: "blur" }],
  name: [{ required: true, message: "主要联系人不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: ["blur", "change"] },
  ],
  email: [
    { required: true, message: "电子邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d|(?=.*[!@#$%^&*])).{8,}$/,
      message: "密码至少包含大小写字母、数字或特殊字符的其中2种，长度不少于8位",
      trigger: "blur",
    },
  ],
  unitType: [{ required: true, message: "单位类型不能为空", trigger: "change" }],
  unitProperty: [{ required: true, message: "单位性质不能为空", trigger: "change" }],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
  agreement: [
    { required: true, message: "请勾选协议", trigger: "change" },

    {
      validator: (rule, value, callback) => {
        console.log(value, 112233);
        if (!value) {
          callback(new Error("请勾选协议"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  independentLegalEntity: [{ required: true, message: "请选择是否为独立法人", trigger: "change" }],
};
const handleUploadSuccess = (response, fileKey, fileName) => {
  console.log(response, fileKey);
  form.value[fileKey] = response;
};
const handleLongTimeChange = () => {
  if (form.value.isLongTime === 1) {
    form.value.periodOfValidity = null; // 清空日期选择器的值
  }
};
const handlePreview = (file) => {
  dialogImageUrl.value = baseUrl + file.url;
  dialogVisible.value = true;
};
const handleRemove = (file, fileKey) => {
  console.log(file, fileKey);
  // 从业务逻辑中移除文件
  form.value[fileKey] = [];
};
const onSubmit = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      addVender({
        ...form.value,
        industryType: form.value.industryType.join(","), // 转换为字符串
        periodOfValidity: form.value.isLongTime == 1 ? "" : moment(form.value.periodOfValidity).format("YYYY-MM-DD HH:mm:ss"), // 格式化时间，包含时分秒
        authorization: form.value.authorization[0].url,
        businessLicense: form.value.businessLicense[0].url,
        certLevel: form.value.certLevel.length ? form.value.certLevel[0].url : "",
      })
        .then((res) => {
          if (res.code === 200) {
            showMessage("注册成功", "success");
            navto("/login");
          } else {
            showMessage(res.msg, "error");
          }
        })
        .catch((err) => {
          // 打印错误，查看结构
          // console.log("错误信息:", err);

          // 提取错误信息
          let errorMessage = "";
          if (typeof err === "string") {
            errorMessage = err;
          } else if (err.response && err.response.data && err.response.data.message) {
            errorMessage = err.response.data.message;
          } else if (err.message) {
            errorMessage = err.message;
          }

          // 错误判断
          if (errorMessage.includes("验证码错误") || errorMessage.includes("验证码已失效")) {
            getCode(); // 重新获取验证码
          } else {
            console.error("其他错误:", errorMessage);
          }
        });
    } else {
      // 获取第一个错误字段的 key
      const firstErrorKey = Object.keys(fields)[0];
      if (firstErrorKey) {
        const errorMsg = fields[firstErrorKey][0].message; // 获取错误信息
        showMessage(errorMsg, "error"); // 弹出错误提示
      }
    }
  });
};

const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      form.value.uuid = res.uuid;
    }
  });
};
const navto = (url) => {
  if (url == "/login") {
    if (type.value == "vendor") {
      router.push("/");
      return;
    }
  }
  router.push(url);
};
onMounted(() => {
  // 如果字典数据为空，主动加载
  if (!dataStore.supplier_cert.length) {
    dataStore.fetchData();
  }
  getCode();
});
</script>

<style lang="scss" scoped>
.page {
  height: calc(100vh - 56px);
  background: url("../../assets/back-login.png") no-repeat center center;
  background-size: cover;
}
.registration-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  //   height: calc(100vh - 56px);
  width: 100%;
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat center center;
  background-size: cover;
  padding: 20px 0;

  .form-container {
    background: #fff;
    padding: 2rem;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    width: 70%;
    max-width: 1300px;
    display: flex;
    align-items: center;
    justify-content: center;
    .form {
      width: 450px;
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 25px;
}
.back-link {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
  width: 70%;
  max-width: 1300px;
  span {
    margin-left: 20px;
  }
}
.input-icon {
  height: 39px;
  width: 14px;
  margin-left: 2px;
}
.register-code {
  height: 35px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.register-code-img {
  height: 38px;
}
.register-tip {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tips {
  font-size: 14px;
  color: #909399;
  margin-left: 5px;
}
</style>
